<template>
  <el-dialog
    class="dia-style"
    title="修改密码"
    :visible.sync="open"
    width="680px"
    append-to-body
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @close="reset"
    :show-close="isShow">
    <div v-if="errorMsg != ''" style="color: #ff4949; padding: 10px 0">{{ errorMsg }}</div>
    <el-form ref="resetPwdForm" :model="user" :rules="rules" label-width="80px">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="user.oldPassword" placeholder="请输入旧密码" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="user.newPassword" placeholder="请输入新密码" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="user.confirmPassword" placeholder="请确认密码" type="password" show-password />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button v-show="isShow" @click="open = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateUserPwd } from '@/api/system/account'
import { passwordRegx } from '@/utils/validate'
import { encrypt } from '@/utils/jsencrypt'
import { runInThisContext } from 'vm'
import { addlockKey, getLockKey } from '@/api/system/sysUkey'
import {getConfigKey} from "@/api/system/config";
import Cookies from 'js-cookie'

export default {
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.user.newPassword !== value) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    const isSamePassword = (rule, value, callback) => {
      if (this.user.oldPassword == value) {
        callback(new Error('新密码不能和旧密码一样'))
      } else {
        callback()
      }
    }
    return {
      open: false,
      errorMsg: '',
      user: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined,
      },
      // 表单校验
      rules: {
        oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
        newPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
         /*  {
            pattern: passwordRegx,
            message: '密码需同时包含数字、大写字母、小写字母和特殊字符，且长度在8-15位字符之间',
            trigger: 'blur',
          }, */
          { required: true, validator: isSamePassword, trigger: 'blur' },
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { required: true, validator: equalToPassword, trigger: 'blur' },
        ],
      },
      isShow: true,
    }
  },
  created() {
    // 注册监听事件
    window.addEventListener('onmessageWS', this.getSocketData)
    if (Cookies.get("keySn")){
      this.getPwdReg()
    }
  },
  beforeDestroy() {
    window.removeEventListener('onmessageWS', this.getSocketData)
  },
  methods: {
    show(param) {
      if (param) {
        this.isShow = param.isShow
        this.errorMsg = param?.msg
      }
      this.open = true
    },
    submitForm() {
      const account = this.$store.state.user.name
      this.$refs['resetPwdForm'].validate((valid) => {
        if (valid) {
          // 判断当前用户是否KEY登录
          let keySn = Cookies.get('keySn')
          if (keySn) {
            if (!this.keySn) {
              this.$message.warning("正在检测Key,请稍后")
              return;
            }
            if (!this.lockKey) {
              this.keyResetPin(this.user.newPassword)
            }
          }else{
            updateUserPwd(account, encrypt(this.user.oldPassword), encrypt(this.user.newPassword)).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
            })
          }
        }
      })
    },
    reset() {
      this.errorMsg = ''
      this.$refs['resetPwdForm'].resetFields()
    },
    /**
     *  收到websocket消息处理
     */
    getSocketData(e) {
      const data = e && eval('(' + e.detail.data + ')');
      let resultData = data.result_data;
      //查询key序列号
      if (data.cmd_name === "key_scan") {
        this.keySn = resultData.key_sn
        if (!this.keySn) {
          this.setIntervalKey = null
          this.lockKey = false
          this.initLockKey = false
        } else {
          if (!this.initLockKey) {
            this.getKey()
          }
        }
      }
      if (data.cmd_name === "key_change_pin") {
        if (0 !== data.err_code) {
          if (data.err_des.toString().trim() === '应用不存在') {
            this.lockKey = true
            this.errorMsg = "修改失败，请重试。"
          }
          //查询key是否被锁
          if (resultData.retry_count === 0) {
            if (!this.lockKey) {
              //锁定KEY
              addlockKey(this.keySn).then(res => {
                this.lockKey = true
                this.errorMsg = "KEY已被锁定，请在" + res + "分钟后重试"
                this.lockKeyInterval()
              })
            } else {
              this.getKey()
            }
          } else {
            this.errorMsg = "KEY密码不正确，剩余验证次数：" + resultData.retry_count + "次"
          }
        } else {
          this.$modal.msgSuccess("修改成功")
          this.open = false
        }
      }
    },
    //key重置pin
    keyResetPin() {
      let cmdData = { "key_sn": this.keySn, "pin_old": this.user.oldPassword, "pin_new": this.user.newPassword }
      this.$websocket.sendKeyProduct("key_change_pin", cmdData)
    },
    getKey() {
      if (this.keySn) {
        getLockKey(this.keySn).then(res => {
          this.lockKey = res.lockKey
          this.initLockKey = true
          if (res.lockKey) {
            if (res.minute !== 0) {
              this.errorMsg = "KEY已被锁定,请在" + res.minute + "分钟后重试"
            } else {
              this.errorMsg = ''
              this.lockKey = false
              let cmdData = { "key_sn": this.keySn }
              this.$websocket.sendKeyProduct("key_unlock_pin", cmdData)
              if (this.setIntervalKey) {
                clearInterval(this.setIntervalKey)
              }
            }
          } else {
            if (this.setIntervalKey) {
              clearInterval(this.setIntervalKey)
            }
          }
        })
      }
    },
    // 获取密码强度 切换校验规则
    getPwdReg() {
      getConfigKey("sys.security.passwordLength").then((res) => {
        const pwdLength = res.configValue
        sessionStorage.setItem('pwdLength', pwdLength) // 保存密码强度配置
        const regExt = new RegExp("(?=.*\\d)(?=.*[a-zA-Z])(?=.*[^\\da-zA-Z\\s]).{" + pwdLength + ",}")
        this.rules.newPassword.push({
          pattern: regExt,
          message: `口令长度设置应该不少于${pwdLength}位，至少是大小写英文字母、数字和特殊字符中两者以上的组合`,
          trigger: "blur"
        })
      })
    }
  }
};
</script>
